package com.cai.btautolink;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.util.Objects;


public class AutoConfirmAccessibilityService extends AccessibilityService {

    private static final String TAG = "AutoConfirm";

    public static final String ACT_CLOSE_AUTO = "com.cai.CLOSE_AUTO";

    // 目标弹窗的关键词（根据需要修改，如蓝牙配对的“配对”“确认”）
    private static final String[] CONFIRM_KEYWORDS = {"确认", "配对", "允许", "OK", "Pair"};
    // 需要忽略的弹窗关键词（可选）
    private static final String[] IGNORE_KEYWORDS = {"取消", "Cancel"};

    private BootBroadcastReceiver receiver = new BootBroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: ");
            if (Objects.equals(intent.getAction(), ACT_CLOSE_AUTO)) {
                disableSelf();
            }
        }
    };

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        // 只处理窗口弹出事件
        if (event.getEventType() != AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            return;
        }

        // 获取当前窗口的根节点
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode == null) return;

        // 遍历窗口中的所有按钮，寻找“确认”按钮
        findAndClickConfirmButton(rootNode);
    }

    // 查找并点击“确认”按钮
    private void findAndClickConfirmButton(AccessibilityNodeInfo node) {
        if (node == null) return;

        // 检查当前节点是否为按钮，且文本包含确认关键词
        if (node.getClassName().equals("android.widget.Button")) {
            CharSequence text = node.getText();
            if (text != null) {
                String buttonText = text.toString();

                // 忽略“取消”等按钮
                for (String ignore : IGNORE_KEYWORDS) {
                    if (buttonText.contains(ignore)) {
                        return;
                    }
                }
                // 匹配“确认”关键词，执行点击
                for (String keyword : CONFIRM_KEYWORDS) {
                    if (buttonText.contains(keyword)) {
                        node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        return;
                    }
                }
            }
        }

        // 递归检查子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            findAndClickConfirmButton(node.getChild(i));
        }
    }

    @Override
    public void onInterrupt() {
        // 服务被中断时调用（如用户关闭无障碍服务）
        Log.e(TAG, "服务被中断！可能被系统杀死");
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.d(TAG, "onServiceConnected: ");

        IntentFilter filter = new IntentFilter();
        filter.addAction(ACT_CLOSE_AUTO);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver,  filter);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: ");
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        return super.onUnbind(intent);
    }
}
